package com.example.jmeter.enums;

import com.example.jmeter.exception.OSCmdException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: spring-agent
 * @description:
 * @author: zt22328 赵儒定
 * @create: 2023-04-19 10:44
 **/
public enum OsType {

    Window {

        private String ERROR_EXIT = "errorlevel=";
        @Override
        public List<String> executeScript(String cmdStr, String ... endpoints) {
            try {
                ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", cmdStr);
                builder.redirectErrorStream(true);
                Process p = builder.start();
                try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream(),"gbk"));){
                    String line;
                    List<String> list = new ArrayList<>();
                    while (true) {
                        line = r.readLine();
                        if (line == null) {
                            continue;
                        }else if (endpoints(line, endpoints, ERROR_EXIT)) {
                            r.close();
                            break;
                        }
                        System.out.println(line);
                        list.add(line);
                    }
                    return list;
                }
            } catch (Exception ex) {
                throw new OSCmdException(this, cmdStr, ex);
            }
        }


    },

    Linux {
        @Override
        public List<String> executeScript(String cmdStr, String ... endpoints) {
            // todo
            return null;
        }
    },

    ;

    private static boolean endpoints(String line, String[] endpoints, String error_exit) {
        List<String> list = new ArrayList<>(Arrays.asList(endpoints));
        list.add(error_exit);
        return list.stream().filter(e->line.startsWith(e)).findFirst().isPresent();
    }

    public static OsType getCurrentOsType() {
        String osName = System.getProperty("os.name");
        return osName.toLowerCase().startsWith("win") ? Window : Linux;
    }

    public static List<String> execute(String  cmdStr, String ... endpoint) {
        return getCurrentOsType().executeScript(cmdStr, endpoint);
    }

    public abstract List<String> executeScript(String  cmdStr, String ... endpoint);

}
